package com.xyy.saas.payment.adpater.xydLoan;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.adpater.xydLoan.core.constants.XydApiAddress;
import com.xyy.saas.payment.adpater.xydLoan.core.constants.XydCreditLoanConstants;
import com.xyy.saas.payment.adpater.xydLoan.core.dto.XydAuthCreditDto;
import com.xyy.saas.payment.adpater.xydLoan.core.req.XydAccountBalanceReq;
import com.xyy.saas.payment.adpater.xydLoan.core.req.XydAuthCreditReq;
import com.xyy.saas.payment.adpater.xydLoan.core.req.XydGetFileReq;
import com.xyy.saas.payment.adpater.xydLoan.core.resp.XydLoanResponse;
import com.xyy.saas.payment.cores.constants.Constants;
import com.xyy.saas.payment.util.xydSign.XydSignUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangzeqi
 */
@Slf4j
public class XydLoanDemo {

    public static final String urlPrefix = "https://zeus-gateway.test.xiaoyudian.com/open-platform-pre";
    public static final String accessKey = "b2d5bd71cf4ae7d43bdcfa702a4612d9";

    public static void main(String[] args) {
//        testJsonParse();
//        getFile();
        queryAccountBalance();
//         applyH5();
    }



    private static void testJsonParse() {
        XydLoanResponse data = new XydLoanResponse();
        data.setData(Collections.singletonList(new XydAuthCreditDto()
                .setDeviceNo("DV001")
                .setThirdUserNo("YBMU001")
                .setBusinessLicense("952001H")));
        data.setCode("0");
        String jsonString = JSON.toJSONString(data);
        System.out.println(jsonString);

        XydLoanResponse xydLoanResponse = JSON.parseObject(jsonString, XydLoanResponse.class);

        System.out.println(xydLoanResponse);

        Object rdata = xydLoanResponse.getData();

        if (rdata instanceof JSONObject) {
            JSONObject rdataJsonObj = (JSONObject) rdata;
            XydAuthCreditDto xydAuthCreditDto = rdataJsonObj.toJavaObject(XydAuthCreditDto.class);
            System.out.println(xydAuthCreditDto.getDeviceNo());
        } else if (rdata instanceof JSONArray) {
            JSONArray rdataJsonObjs = (JSONArray) rdata;
            List<XydAuthCreditDto> xydAuthCreditDtos = rdataJsonObjs.toJavaList(XydAuthCreditDto.class);
            System.out.println(xydAuthCreditDtos.get(0).getDeviceNo());
        }
    }

    private static void applyH5() {
        String url = urlPrefix + XydApiAddress.authCredit;

        XydAuthCreditReq xydAuthCreditReq = XydAuthCreditReq.mock();
        String jsonString = JSON.toJSONString(xydAuthCreditReq);

        log.info("applyH5 request param:{}", jsonString);

        try {

            Map<String, String> headers = creatRequestHeaders(jsonString, accessKey);

            try (
                    HttpResponse httpResponse = HttpUtil.createPost(url)
                            .timeout(5000)
                            .addHeaders(headers)
                            .body(jsonString)
                            .execute()) {

                String resp = httpResponse.body();

                log.info("applyH5 response body:{}", resp);
            }

        } catch (Exception e) {
            log.error("XydLoanDemo applyH5 error", e);
        }

    }

    private static void queryAccountBalance() {
        String url = urlPrefix + XydApiAddress.QUERY_ACCOUNT_BALANCE;

        XydAccountBalanceReq balanceReq = new XydAccountBalanceReq();
        balanceReq.setAccountNo(Constants.XYD_REFUND_ACCOUNT);
//        balanceReq.setPlatformCode("12");
        String jsonString = JSON.toJSONString(balanceReq);


        try {
            Map<String, String> headers = creatRequestHeaders(jsonString, accessKey);

            try (
                    HttpResponse httpResponse = HttpUtil.createPost(url)
                            .timeout(5000)
                            .addHeaders(headers)
                            .body(jsonString)
                            .execute()) {

                String resp = httpResponse.body();

                log.info("queryAccountBalance req:{} response:{}", JSON.toJSONString(balanceReq), resp);
            }

        } catch (Exception e) {
            log.error("queryAccountBalance error req:{}", JSON.toJSONString(balanceReq), e);
        }
    }
    private static void getFile() {
        String url = urlPrefix + XydApiAddress.GET_FILE;

        XydGetFileReq fileReq = new XydGetFileReq();
        fileReq.setFileType("financeKeeperFile");
        fileReq.setCheckDate("2025-04-01");
        fileReq.setCheckCycle("monthly");
//        fileReq.setCheckCycle("daily");
        fileReq.setProductNo("GYL-YCD-CGD");
        fileReq.setPlatformCode("yaobangmang");
        String jsonString = JSON.toJSONString(fileReq);

        log.info("getFile request url:{} param:{}", url, jsonString);

        try {
            Map<String, String> headers = creatRequestHeaders(jsonString, accessKey);

            try (
                    HttpResponse httpResponse = HttpUtil.createPost(url)
                            .timeout(5000)
                            .addHeaders(headers)
                            .body(jsonString)
                            .execute()) {

                String resp = httpResponse.body();

                log.info("getFile response body:{}", resp);
            }

        } catch (Exception e) {
            log.error("getFile applyH5 error", e);
        }

    }

    @SneakyThrows
    private static Map<String, String> creatRequestHeaders(String jsonString, String accessKey) {
        String currentTimeStr = String.valueOf(System.currentTimeMillis());

        Map<String, String> headers = new HashMap<>();
        headers.put("XS-ACCESSKEY", accessKey);
        headers.put("XS-SIGN", XydSignUtil.sign(jsonString, currentTimeStr, XydCreditLoanConstants.B2B_TEST_PRIVATE_KEY));
        headers.put("XS-TIMESTAMP", currentTimeStr);
        return headers;
    }

}
